import { _decorator, Component, Node, Vec3, find, Label, color, director, sys, native, EventTarget, EventTouch, 
    AudioClip, AudioSource, resources, TTFFont, Sprite, instantiate, tween, Animation, UITransform, 
    Button,
    ImageAsset,
    assetManager,
    AssetManager,
    Prefab} from 'cc';
const { ccclass, property } = _decorator;

import { BLANK_TYPE } from './Enums';
import { requestInit, host, game } from './Apis'
import { GameResultParams, RemarkGameResultParams } from './Interface'
import Global from '../common/Global'
import BaseBean from '../model/BaseBean'
export const eventTargetUtil = new EventTarget();
import { STAR_NUM } from './Enums';
import { error } from 'console';
@ccclass('Utils')
export class Utils extends Component {
    start() {
        
    }

    update(deltaTime: number) {
        
    }
}

/**
 * 批量绑定节点半透明
 * @param nodeList 节点列表
 * @param startCallbackList touch_start事件回调 列表
 * @param endCallbackList touch_end事件回调 列表
 * @param moveCallback touch_move事件回调 列表
 */
export const bindNodeOpacity = (nodeList: Array<Node>, startCBList?: Array<Function>, endCBList?: Array<Function>, moveCallback?: Array<Function>) => {
    nodeList?.map((node, index) => {
        // removeToucheEvent(node);
        node?.on(Node.EventType.TOUCH_START, () => {
            if (node.parent?.getChildByName("mask")) return;
            let mask = instantiate(node);
            mask.name = "mask";
            mask.parent = node.parent;
            mask.getComponent(Sprite).color = color("#00000050");
            startCBList && startCBList[index] && startCBList[index]();
        }, this);

        node?.on(Node.EventType.TOUCH_END, (e: EventTouch) => {
            node.parent.removeChild(node.parent.getChildByName("mask"));
            endCBList && endCBList[index] && endCBList[index](e);
            
        }, this);
        
        node?.on(Node.EventType.TOUCH_MOVE, (e: EventTouch) => {
            let touchLocation = e.getUILocation ();
            let btnWorldPos = node.parent.getComponent(UITransform).convertToWorldSpaceAR(node.position);
            let btnSize = node.getComponent(UITransform).contentSize;
            if (touchLocation.x < btnWorldPos.x - btnSize.width / 2 ||
                touchLocation.x > btnWorldPos.x + btnSize.width / 2 ||
                touchLocation.y < btnWorldPos.y - btnSize.height / 2 ||
                touchLocation.y > btnWorldPos.y + btnSize.height / 2
            ) {
                node.parent.removeChild(node.parent.getChildByName("mask"));
            }
            moveCallback && moveCallback[index] && moveCallback[index]();
        }, this);
    })
}

// 动态显示星星个数
const showStar = (res: any) => {
    if (res?.data?.star === STAR_NUM.ONE) {
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/LeftStart`).active = true;
        find("Canvas/LastResultDialog/Start/LeftStart").active = true;
    }
    if (res?.data?.star === STAR_NUM.TWO) {
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/LeftStart`).active = true;
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/CenterStart`).active = true;
        find("Canvas/LastResultDialog/Start/LeftStart").active = true;
        find("Canvas/LastResultDialog/Start/CenterStart").active = true;
    }
    if (res?.data?.star === STAR_NUM.THREE) {
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/LeftStart`).active = true;
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/CenterStart`).active = true;
        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Start/RightStart`).active = true;

        find("Canvas/LastResultDialog/Start/LeftStart").active = true;
        find("Canvas/LastResultDialog/Start/CenterStart").active = true;
        find("Canvas/LastResultDialog/Start/RightStart").active = true;
    }
}
const afterIsCanPlay = (value: string, res: any) => {
    let rawData: BaseBean<boolean> = JSON.parse(value)
    let isCanPlay = rawData?.data;
    const levelId = Global.gameLevels && Global.gameLevels[Global.currentLevelIndex + 1]?.id;
    director.pause();
    find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Mask`).on(Node.EventType.TOUCH_START, () => {})
    find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Mask`).on(Node.EventType.TOUCH_MOVE, () => {})
    find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Mask`).on(Node.EventType.TOUCH_END, () => {})
    if (isCanPlay && levelId) {
        let resultDialog: Node;
        let rateLabel: Node;
        let timeLabel: Node;
        let resultDialogPath: string = `Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog`
        resultDialog = find(resultDialogPath);
        let rateLabelPath: string = `${resultDialogPath}/RateRect/rate`
        let timeLabelPath: string = `${resultDialogPath}/TimeRect/time`
        timeLabel = find(timeLabelPath);
        rateLabel = find(rateLabelPath);
        rateLabel.getComponent(Label).string = res?.data?.rightRate;
        timeLabel.getComponent(Label).string = res?.data?.takeTimeFormat;
        resultDialog.parent.insertChild(resultDialog, resultDialog.parent.children.length);
        resultDialog.active = true;

        find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/ExitButton`).on(Node.EventType.TOUCH_END, () => {
            find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/ExitButton`).off(Node.EventType.TOUCH_END);
            resultDialog.active = false;
            eventTargetUtil.emit("STOP_GAME");
            director.resume();
            director.loadScene("park");
        })
        showStar(res);
        if (res?.data?.pass && !res?.data?.nextGameLevel) {
            find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Button`).active = false;
            let position = find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/ExitButton`).position;
            find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/ExitButton`).position = new Vec3(0, position?.y , position?.z);
        } else if (res?.data?.pass && res?.data?.nextGameLevel) {
            find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Button`).active = true;
        }
        if (!res?.data?.pass && res?.data?.star <= STAR_NUM.TWO) {
            find(`Canvas/${res?.data?.pass ? 'Success' : 'Failed'}Dialog/Button`).active = true;
        }
    } else {
        let lastDialog = find("Canvas/LastResultDialog");
        lastDialog.parent.insertChild(lastDialog, lastDialog.parent.children.length);
        lastDialog.active = true;
        
        find("Canvas/LastResultDialog/Rate/Value").getComponent(Label).string = res?.data?.rightRate;
        find("Canvas/LastResultDialog/Time/Value").getComponent(Label).string = res?.data?.takeTimeFormat;

        showStar(res);
        if (res?.data?.pass) {
            find("Canvas/LastResultDialog/SuccessTitle").active = true;
            find("Canvas/LastResultDialog/SuccessDesc").active = true;
            find("Canvas/LastResultDialog/Rate/Value").getComponent(Label).color = color("#71C735");
            find("Canvas/LastResultDialog/Time/Value").getComponent(Label).color = color("#71C735");
        } else {
            find("Canvas/LastResultDialog/FailTitle").active = true;
            find("Canvas/LastResultDialog/FailDesc").active = true;
            find("Canvas/LastResultDialog/Rate/Value").getComponent(Label).color = color("#EF4D22");
            find("Canvas/LastResultDialog/Time/Value").getComponent(Label).color = color("#EF4D22");
        }
        find("Canvas/LastResultDialog/ExitButton").on(Node.EventType.TOUCH_END, () => {
            find("Canvas/LastResultDialog/ExitButton").off(Node.EventType.TOUCH_END);
            lastDialog.active = false;
            director.resume();
            eventTargetUtil.emit("STOP_GAME");
            director.loadScene("park");
        })
    }
    
}
// 获取游戏结果之后处理逻辑
const afterGameResult = (value: string, errorCallback?: Function) => {
    let res = JSON.parse(value);
    if (res?.code === 0) {
        if (sys?.platform == sys?.Platform?.ANDROID && !Global?.netIsAvailable()) {
            const result = native.reflection.callStaticMethod(
                "com/davinci/xpad/data/local/CocosLocal", // 类名
                "isCanPlay", // 方法名
                "()Ljava/lang/String;" // 方法签名
            );
            console.log("Result from game: " + result);
            afterIsCanPlay(result, res);
        } else {
            fetch(Global.URL_GAME_IS_CAN_PLAY, { headers: { 'username': Global.deviceId } }).then((response: Response) => {
                return response.text()
            }).then((value) => {
                afterIsCanPlay(value, res);
            })
        }
    } else {
        errorCallback && errorCallback();
    }
}
/**
 * 获取游戏结果
 * @param body 请求参数
 * @param successCallback 可选，成功回调 
 * @param errorCallback 可选，失败回调
 */
export const getGameResult = (url: string, body: Array<GameResultParams> | RemarkGameResultParams, successCallback?: Function, errorCallback?: Function) => {
    let reqInit = JSON.parse(JSON.stringify(requestInit));
    reqInit.method = "POST";
    reqInit.body = JSON.stringify(body);
    reqInit.headers['content-type'] = 'application/json';
    if (sys?.platform == sys?.Platform?.ANDROID && !Global?.netIsAvailable()) {
        const result = native.reflection.callStaticMethod(
            "com/davinci/xpad/data/local/CocosLocal", // 类名
            url.indexOf("select") > -1 ? "select" : "judgment", // 方法名
            "(Ljava/lang/String;)Ljava/lang/String;", // 方法签名
            reqInit.body, // 第一个参数
        );
        console.log("Result from game: " + result);
        afterGameResult(result, errorCallback);
    } else {
        fetch(`${host.develop}${url}`, reqInit).then((response: Response) => {
            return response.text()
        }).then((value) => {
            successCallback && successCallback();
            afterGameResult(value, errorCallback);
        })
    }
    
}
// 判断次数：是否可以继续玩
export const loadIsCanPlay = (that: any, callback?: Function) => {
    if (sys?.platform == sys?.Platform?.ANDROID && !Global?.netIsAvailable()) {
        const result = native.reflection.callStaticMethod(
            "com/davinci/xpad/data/local/CocosLocal", // 类名
            "isCanPlay", // 方法名
            "()Ljava/lang/String;" // 方法签名
        );
        let rawData: BaseBean<boolean> = JSON.parse(result)
        that.isCanPlay = rawData.data;
        callback && callback();
    } else {
        fetch(Global.URL_GAME_IS_CAN_PLAY, { headers: { 'username': Global.deviceId } }).then((response: Response) => {
            return response.text()
        }).then((value) => {
            let rawData: BaseBean<boolean> = JSON.parse(value)
            that.isCanPlay = rawData.data;
            callback && callback();
        })
    }
}

export const getStrLength = (str: string): number => {
    if (!str) return 0;
    var length: number = 0;
    for (var i: number = 0; i < str.length; i++) {
        var n: number = +str.charCodeAt(i);
        if (19968 <= n && n < 40869) length += 2;
        else length++;
    }
    return length;
}
// 监听处理wifi按钮
export const handleWifiBtn = (type: string, content: string, that: any) => {
    if (type === 'wifi') {
        Global.wifiStatus = content
        if (content === 'on') {
            that.wifiOn.active = true
            that.wifiOff.active = false
        } else {
            that.wifiOn.active = false
            that.wifiOff.active = true
        }
    }
    return
}

// 切换wifi按钮
export const switchWifiBtn = (that: any) => {
    if (Global.wifiStatus === 'on') {
        that.wifiOn.active = true
        that.wifiOff.active = false
    } else {
        that.wifiOn.active = false
        that.wifiOff.active = true
    }
}

 
// 路由历史记录栈
export let routeHistory = [];

// 加载场景
export const loadScene = (scenceName: string, that: any, preName?: string, cb?: Function ) => {
    let pre = director.getScene();
    routeHistory.push(preName || pre.name);
    scenceName && director.loadScene(scenceName, (err, scene)=>{
        cb && cb();
    })
}
 
// 返回上一个场景
export const  popRoute = () => {
    // 场景卸载完成后，弹出栈顶的场景名称
    let prevScene = routeHistory.pop() || "main";
    console.log("prevScene======================", prevScene)
    Global.routeFrom = prevScene;
    director.loadScene(prevScene);
}
// 缓动easeIn
export const easeIn = (time: number, beginValue: number, currentVaue: number, duration: number) => {
    let factor = Math.sqrt(1 - time * time) || 0;
    return (1 - factor * factor * factor) * beginValue * duration + currentVaue;
}

// 判断哪种挖空
export const getBlankType = (exercise: string) => {
    if (exercise?.indexOf('?input?') > -1) {
        const tempArr = exercise?.split("?input?");
        if (tempArr?.length === 2) {
            if (tempArr[0] === "" && tempArr[1] !== "") {
                return BLANK_TYPE.PRE_BLANK;
            }
            if (tempArr[1] === "" && tempArr[0] !== "") {
                return BLANK_TYPE.SUF_BLANK;
            }
            if (tempArr[0] !== "" && tempArr[1] !== "") {
                return BLANK_TYPE.CENTER_BLANK;
            }
        }
    } else {
        return BLANK_TYPE.SUF_BLANK;
    }
}

// 播放音频
export const playAudio = (node: Node, clip: AudioClip, cb?: Function, as?: AudioSource) => {
    const audioSource = as || node.getComponent(AudioSource)!;
    audioSource.clip = clip;
    if (cb) {
        audioSource?.node?.once(AudioSource.EventType.ENDED, () => {
            audioSource.stop();
            cb(audioSource);
            // audioSource.node.off(AudioSource.EventType.ENDED, this);
        }, this);
    }
    audioSource.play();
}

// 根据字体名称获取字体资源
export const getFont = (name: string) => {
    let font = Global.systemFonts?.find((ft) => {
        return ft.name === name;
    })
    return font;
}

// 加载字体
export const loadFont = () => {
    let path = 'fonts'
    return new Promise((resolve, reject) => {
        return resources.loadDir(path, TTFFont, (err, fonts) => {
            if (err) {
                reject(false);
                return;
            }
            Global.systemFonts = fonts;
            resolve(fonts);
        });
    })
    
}
// 注销touch事件
export const removeToucheEvent = (node: Node) => {
    node?.off(Node.EventType.TOUCH_START);
    node?.off(Node.EventType.TOUCH_MOVE);
    node?.off(Node.EventType.TOUCH_END);
    node?.off(Node.EventType.TOUCH_CANCEL);
}
// 随机1~len
export const randomIndex = (len: number = 10) => {
    let rand = Math.floor(Math.random() * len)
    return rand > 1 ? rand - 1 : rand;
}

// 设置属性键值对
export const setProperty = (key: string, value: string) => {
    native.reflection?.callStaticMethod(
        "com/davinci/xpad/data/local/CocosLocal", // 类名
        "setProperty", // 方法名
        "(Ljava/lang/String;Ljava/lang/String;)V", // 方法签名
        key, // 参数
        value // 参数
    );
}
// 获取属性值
export const getProperty = (key: string) => {
    const result = native.reflection?.callStaticMethod(
        "com/davinci/xpad/data/local/CocosLocal", // 类名
        "getProperty", // 方法名
        "(Ljava/lang/String;)Ljava/lang/String;", // 方法签名
        key // 参数
    );
    console.log("Result from getProperty: " + result);
    return result;
}

export const onNative = (that: any, mainEventTarget: EventTarget, movieEventTarget: EventTarget) => {
    if (native.bridge) {
        native.bridge.onNative = (type: string, content: string): void => {
            native?.bridge?.sendToNative('log.e', `MainController.ts onNative type = ${type} content = ${content} `)
            let scenceName = director.getScene().name;
            let sceneList = ["movieTicket", "userInfo", "daPeriphery", "bindParent", "contactDa", "keepingBook"]
            if (type === 'toggleStreetLamp' && that?.fire) {
                that.fire.active = !that.fire.active
            } else if (type === 'wifi') {
                mainEventTarget?.emit(Global.MESSAGE_SET_WIFi_STATUS, content);
                let header = null;
                if (sceneList.indexOf(scenceName) > -1) {
                    header = that.node.parent.getChildByName("Head");
                } else {
                    header = that.node.getChildByName("Head");
                }
                native?.bridge?.sendToNative('log.i', `Utils.ts receiver type = ${type} content = ${content} `)
                let controller: any = header?.getComponent("Header");
                controller?.initBtnClick(type, content);
                handleWifiBtn(type, content, that);
                switchWifiBtn(that);
            } else if (type === 'bindSuccess') {
                //第一次绑定成功，刷新首页用户信息
                mainEventTarget?.emit(Global.MESSAGE_BIND_SUCCESS)
            } else if (type === 'smartCalculation') {
                //跳速算选择页
                Global.routeFrom = "market";
                routeHistory.push("market");
                that.scheduleOnce(() => {
                    eventTargetUtil.emit("Cocos_Back");
                }, 0.5);
                director.preloadScene("rapidCalculate", (completedCount, totalCount) => {
                    const progress = completedCount / totalCount
                }, () => {
                    director.loadScene("rapidCalculate", (err, scene)=>{
                        if (err) {
                            console.error("Failed to load scene:", err);
                            return;
                        }else{
                            native?.bridge?.sendToNative('closeCocosLoading')
                        }
                    })
                })
            } else if (type === "fastPracticeFinished") { // 练一练 结果弹窗返回消息
                Global.routeFrom = "androidPractise";
                that.loadBg && that.loadBg();
            } else if (type === 'interstellarTravel') {
                //跳星际旅行选择页
                Global.routeFrom = "museum";
                routeHistory.push("museum");
                that.scheduleOnce(() => {
                    eventTargetUtil.emit("Cocos_Back");
                }, 0.5);
                director.preloadScene("interstellarTravel", (completedCount, totalCount) => {
                    const progress = completedCount / totalCount
                }, () => {
                    director.loadScene("interstellarTravel", (err, scene)=>{
                        if (err) {
                            console.error("Failed to load scene:", err);
                            return;
                        }else{
                            native?.bridge?.sendToNative('closeCocosLoading')
                        }
                    })
                })
            } else if (type === 'ufoFliesAway') {
                that.daily.active = false
                that.ufoAway.active = true
                tween(that.ufoAway).delay(3).call(() => {
                    that.ufoAway.getComponent(Animation).stop()
                    that.effectAudioSource.play()
                }).to(2, { position: new Vec3(-826, 395, 0) }).delay(0.3).to(2, { position: new Vec3(-38, 625, 0), scale: new Vec3(0.1, 0.1, 0) }).removeSelf().start()
            } else if (type === 'bgmSwitch') {
                if (content === 'on') {
                    mainEventTarget?.emit(Global.MESSAGE_SET_BGM_SWITCH, true)
                } else {
                    mainEventTarget?.emit(Global.MESSAGE_SET_BGM_SWITCH, false)
                }
            } else if (type === 'earnCoins') {
    
                let pointLabel = find('Canvas/UserInfo/point/pointNumber/pointLabel')?.getComponent(Label);
                if (pointLabel) {
                    let oldValue = parseInt(pointLabel.string)
                    if (isNaN(oldValue)) {
                        oldValue = 0
                    }
    
                    let increment = parseInt(content)
                    if (isNaN(increment)) {
                        increment = 0
                    }
    
                    let newValue = oldValue + increment
                    pointLabel.string = newValue.toString()
                }
            } else if(type === 'loadMainScene'){
                director.loadScene('main')
            } else if (type === 'videoProgress') {
                movieEventTarget?.emit('videoProgress', content);
            } else if (type === 'selectedDate') {
                let dateLabel = find('Canvas/BoxBg/Left/Birthday/Date/DateLabel').getComponent(Label);
                dateLabel.string = content;
            } else if (type === "onResume") {
                Global.mainTouchId = null;
                Global.homeTouchId = null;
                Global.ticketTouchId = null;
            }
            return
        }
    }
    
}
// 查询按钮节点
export const findButtonNode = (parentNode: Node) => {
    let buttons = [];
    let len = parentNode.children?.length || 0;
    for (let i = 0; i < len; i++) {
        let child = parentNode.children[i];
        if (child.getComponent(Button)) {
            buttons.push(child);
        }
        buttons = buttons.concat(findButtonNode(child));
    }
    return buttons;
}
// 移动按钮文字
export const moveBtnText = () => {
    let root = find("Canvas");
    let btnList = findButtonNode(root);
    console.log("btnList======================", btnList)
    btnList.map((btn: Node) => {
        if (!btn) return;
        let labelNode = btn.getChildByName("Label");
        let txt = labelNode.getComponent(Label)?.string;
        if (txt) {
            let pos = JSON.parse(JSON.stringify(labelNode.position));
            btn?.on(Node.EventType.TOUCH_START, () => {
                labelNode.setPosition(pos.x, pos.y - 14);
                btn?.on(Node.EventType.TOUCH_MOVE, (e: EventTouch) => {
                    let touchLocation = e.getUILocation ();
                    let btnWorldPos = btn.parent.getComponent(UITransform).convertToWorldSpaceAR(btn.position);
                    let btnSize = btn.getComponent(UITransform).contentSize;
                    if (touchLocation.x < btnWorldPos.x - btnSize.width / 2 ||
                        touchLocation.x > btnWorldPos.x + btnSize.width / 2 ||
                        touchLocation.y < btnWorldPos.y - btnSize.height / 2 ||
                        touchLocation.y > btnWorldPos.y + btnSize.height / 2
                    ) {
                        labelNode.setPosition(pos);
                    }
                }, this);
            }, this);
            btn?.on(Node.EventType.TOUCH_END, (e: EventTouch) => {
                labelNode.setPosition(pos);
            }, this);
            btn?.on(Node.EventType.TOUCH_CANCEL, (e: EventTouch) => {
                labelNode.setPosition(pos);
            }, this);
        }
    })
}

// 随机排序
export const randomSort = (arr: any[]) => {
    arr.sort(function(a: any, b: any) {
        return Math.random() * 10 - (a + "").length;
    })
}

// 加载图片资源
export const loadImageResource = (url: string, cb?: Function) => {
    return new Promise((resolve, reject) => {
        resources.load(url, ImageAsset, (err, res) => {
            if (err) {
                reject(false);
                return;
            }
            cb && cb(url, res);
            resolve(res);
        });
    })
}

// 批量加载图片资源
export const batchLoadImageResource = (dir: string, gamePaths: string[], cb?: Function) => {
    let loadPromises = [];
    gamePaths.map((path: string) => {
        let res = loadImageResource(dir + path, cb);
        loadPromises.push(res);
    })
    return Promise.all(loadPromises);
}

// 防止多点同时touch触发
export const stopMultipleBtnClick = (nodeList: Node[], cbList: Function[], that: any) => {
    
    nodeList.map((node: Node, index: number) => {
        if (node) {
            removeToucheEvent(node);
            node?.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
                console.log("touchStart Global.touchId", Global.touchId)
                if (Global.touchId !== null) {
                    event.propagationStopped = true;
                } else {
                    Global.touchId = event.getID();
                }
            }, that)
            node?.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
                console.log("touchEnd Global.touchId2", Global.touchId)
                if (Global.touchId !== event.getID()) {
                    event.propagationStopped = true;
                } else {
                    Global.touchId = null;
                    cbList[index] && cbList[index](event);
                }
            }, that);
        }
    })
}
// 加载自定义资源
export const loadAsync = (path: string): Promise<any> => {
    return new Promise<any>((resolve) => {
        let index = path.indexOf('/');
        let bundleName = path.substring(0, index);
        let filePath = path.substring(index + 1);
        assetManager.loadBundle(bundleName, (err: Error, bundle: AssetManager.Bundle) => {
            if (err) { console.log(`loadAsync加载Bundle失败！(${bundleName})`); resolve(null); return; }
            let files = bundle.getDirWithPath('');
            let type = Prefab;
            for (let i = files.length - 1; i > -1; --i) {
                if (filePath === files[i].path) { type = files[i].ctor.prototype.constructor; break; }
            }
            bundle.load(filePath, type, (err: Error, asset: any) => {
                if (err) { console.log(`loadAsync加载资源失败！(${path})`); resolve(null); return; }
                resolve(asset); return;
            });
        });
    });
}

// 播放音频
export const playAudioClip = (clip: AudioClip) => {
    let cutdownAudio = new AudioSource();
    cutdownAudio.clip = clip;
    cutdownAudio.play();
}